#include "canvas.h"

#include <QDebug>

#include <QKeyEvent>

#include "control.h"
#include "snake.h"

Canvas::Canvas(QWidget* parent) : QGLWidget(parent)
{
    setFocusPolicy(Qt::WheelFocus);
}

void Canvas::setControl(Control *c)

{
    control = c;
    cellLenght = control->getCellLenght();
}

void Canvas::setSnake(Snake *s)
{
    snake = s;
}

void Canvas::setWall(QRect w)
{
    wall = w;
}

void Canvas::setDimensions(int w, int h)
{
    gw = w;
    gh = h;
}

void Canvas::setEat(int x, int y)
{
    eat.setX(x);
    eat.setY(y);
    glDraw();
}

void Canvas::setPaused(bool p)
{
    paused = p;
    glDraw();
}

void Canvas::keyPressEvent(QKeyEvent *e)
{
    control->controlKey( e->key() );
}

void Canvas::paintGL()
{
    QPainter painter(this);
    drawBackground();
    drawScreen(painter);
    drawSnake(painter);
    drawEat(painter);
    if(paused){
        painter.setPen( QColor(255, 240, 240) );
        painter.drawText( 10, 20, "PAUSED");
    }
    painter.end();
    glFlush();
}

void Canvas::drawBackground()
{
    if(paused){
        glClearColor(.7f, .7f, .7f, 1.0f);
    }
    else{
        glClearColor(.0f, .5f, .0f, 1.0f);
    }
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}

void Canvas::drawPoint(QPainter& painter, QPoint p, QColor color)
{
    painter.setBrush( QBrush( color ) );
    painter.setPen(Qt::NoPen);
    painter.drawRect(p.x(), p.y(), cellLenght, cellLenght);
}

void Canvas::drawScreen(QPainter &painter)
{
    painter.drawRect(wall.x(), wall.y(), wall.width(), wall.height());
    QColor color;
    if(paused){
        color.setRgb(200, 200, 200);
    }
    else{
        color.setRgb(180, 200, 180);
    }
    for(int i=0; i<gw; i++){
        for(int j=0; j<gh; j++){
            QPoint p(3 + i*(cellLenght+1), 3 + j*(cellLenght+1));
            drawPoint(painter, p, color);
        }
    }
}

void Canvas::drawSnake(QPainter &painter)
{
    QColor color;
    QColor bodyColor;
    QColor headColor;
    if(paused){
        color.setRgb(200, 200, 200);
        bodyColor.setRgb(100, 100, 100);
        headColor.setRgb(100, 100, 255);
    }
    else{
        color.setRgb(180, 200, 180);
        bodyColor.setRgb(0, 0, 0);
        headColor.setRgb(0, 0, 255);
    }
    QVector<QPoint>& body = snake->getBody();
    for(int i=0; i<body.size()-1; i++){
        drawPoint(painter, body[i], bodyColor);
    }
    drawPoint(painter, body[body.size()-1], headColor);
}

void Canvas::drawEat(QPainter &painter)
{
    if(paused){
        drawPoint(painter, eat, QColor(255, 120, 120));
    }
    else{
        drawPoint(painter, eat, Qt::red);
    }
}

